<?php


namespace App\HttpController\Api;

use EasySwoole\Http\AbstractInterface\Controller;
use EasySwoole\Queue\Job;
use App\Utility\MyQueue;
use Extend\Sign\SortSign;
use Extend\Log\OperationLog;
use EasySwoole\EasySwoole\Config;

class QueueProducer extends Controller
{

    public function index()
    {

        //获取配置
        $confInstance = Config::getInstance();
        $signkey = $confInstance->getConf('queue.signkey');
        // $conf = $confInstance->getConf('queue');
        // $this->jsonEnd(false, $conf, '...');

        //接收参数
        $data = $this->request()->getRequestParam();

        //记录日志
        OperationLog::addLog('queue_produce.log', $data);

        //验签
        $sign = $data['sign'] ?? '';
        unset($data['sign']);
        $checkRes = SortSign::checkSign($data, $sign, $signkey);

        if(!$checkRes){
            return $this->jsonEnd(false, [], '签名不正确');
        }

        $jobDataArr = json_decode($data['jobData'], true);

        $job = new Job();
        foreach ($jobDataArr as $v) {
            //处理任务的url
            // $host = $v['host'] ?? '';
            // $protocol = $v['protocol'] ?? 'http';
            // $port = $v['port'] ?? 80;
            // $ssl = $v['ssl'] ?? false;
            // $path = $v['path'] ?? '/';
            $url = $v['url'] ?? '';
            //请求方法
            $method = $v['method'] ?? 'GET';
            //请求参数
            $params = $v['params'] ?? '';

            if (empty($url)) {
                return $this->jsonEnd(false, [], '消息内容不符合规范');
            }

            $jobData = [
                // 'host' => $host,
                // 'protocol' => $protocol,
                // 'port' => $port,
                // 'ssl' => $ssl,
                // 'path' => $path,
                'url' => $url,
                'method' => $method,
                'params' => $params,
                'time' => time(),
            ];

            //投递任务
            $job->setJobData($jobData);
            MyQueue::getInstance()->producer()->push($job);
        }

        return $this->jsonEnd(true, [], '消息投递成功');
    }

    /**
     * 构建返回值
     */
    private function jsonEnd($status, $data, $msg)
    {
        $data = array(
            "status" => $status,
            "data" => $data,
            "msg" => $msg
        );
        $this->response()->write(json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
        $this->response()->withHeader('Content-type', 'application/json;charset=utf-8');
        // $this->response()->withStatus($statusCode);
        $this->response()->end();
    }
}
